package com.devplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.devplatform.pojo.Message;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.MessageService;
import com.devplatform.util.UserContextHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/message")
@RequiredArgsConstructor
public class MessageController {

    private final MessageService messageService;

    //获取系统消息列表（分页）
    @GetMapping("/system")
    public DataVo<Page<Message>> getSystemMessages(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Long userId = UserContextHolder.getUserId();
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getUserId, userId)
                .eq(Message::getType, 1) // 1表示系统消息
                .orderByDesc(Message::getCreateTime);
        Page<Message> messagePage = messageService.page(new Page<>(page, size), queryWrapper);
        return DataVo.ok(messagePage);
    }

    //获取未读消息数量
    @GetMapping("/system/unread/count")
    public DataVo<Long> getUnreadSystemMessageCount() {
        Long userId = UserContextHolder.getUserId();
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getUserId, userId)
                .eq(Message::getType, 1)
                .eq(Message::getIsRead, 0); // 0表示未读
        long count = messageService.count(queryWrapper);
        return DataVo.ok(count);
    }

    //标记消息为已读
    @PutMapping("/{messageId}/read")
    public DataVo<String> markAsRead(@PathVariable Long messageId) {
        Long userId = UserContextHolder.getUserId();
        Message message = messageService.getById(messageId);
        if (message == null || !message.getUserId().equals(userId)) {
            return DataVo.error("消息不存在");
        }
        message.setIsRead(1);
        if (messageService.updateById(message)) {
            return DataVo.ok("标记已读成功");
        }
        return DataVo.error("标记已读失败");
    }


    //批量标记消息为已读
    @PutMapping("/batch-read")
    public DataVo<String> batchMarkAsRead(@RequestBody List<Long> messageIds) {
        Long userId = UserContextHolder.getUserId();
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Message::getId, messageIds)
                .eq(Message::getUserId, userId);
        List<Message> messages = messageService.list(queryWrapper);
        for (Message message : messages) {
            message.setIsRead(1);
        }
        if (messageService.updateBatchById(messages)) {
            return DataVo.ok("批量标记已读成功");
        }
        return DataVo.error("批量标记已读失败");
    }

    //删除消息
    @DeleteMapping("/{messageId}")
    public DataVo<String> deleteMessage(@PathVariable Long messageId) {
        Long userId = UserContextHolder.getUserId();
        Message message = messageService.getById(messageId);
        if (message == null || !message.getUserId().equals(userId)) {
            return DataVo.error("消息不存在");
        }
        if (messageService.removeById(messageId)) {
            return DataVo.ok("删除成功");
        }
        return DataVo.error("删除失败");
    }

    //批量删除消息
    @DeleteMapping("/batch")
    public DataVo<String> batchDeleteMessages(@RequestBody List<Long> messageIds) {
        Long userId = UserContextHolder.getUserId();
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Message::getId, messageIds)
                .eq(Message::getUserId, userId);
        if (messageService.remove(queryWrapper)) {
            return DataVo.ok("批量删除成功");
        }
        return DataVo.error("批量删除失败");
    }

    //创建系统消息（通用）
    @PostMapping("/system/create")
    public DataVo<String> createSystemMessage(@RequestBody Message message) {
        message.setType(1); // 系统消息
        message.setIsRead(0); // 默认未读
        if (messageService.save(message)) {
            return DataVo.ok("消息创建成功");
        }
        return DataVo.error("消息创建失败");
    }
}